package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.Exception.MyException;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Permission;
import com.itheima.health.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Author ： ZAG WELL
 * @Date : 2020/12/6
 */
@Service(interfaceClass = PermissionService.class)
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public List<Permission> findAll() {
        return permissionDao.findAll();
    }

    @Override
    public void add(Permission permission) {
        permissionDao.add(permission);
    }

    @Override
    public PageResult<Permission> findPage(QueryPageBean queryPageBean) {
        // 使用分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        // 是否有查询条件 【注意】！不要漏掉了
        if(!StringUtils.isEmpty(queryPageBean.getQueryString())){
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        // 调用dao查询
        Page<Permission> checkItemPage = permissionDao.findByCondition(queryPageBean.getQueryString());
        long total = checkItemPage.getTotal();// 总计录数
        List<Permission> rows = checkItemPage.getResult();// 分页结果集
        return new PageResult<Permission>(total,rows);
    }

    @Override
    public void update(Permission permission) {
        permissionDao.update(permission);
    }

    @Override
    public void deleteById(int id) throws MyException {
        // 判断 是否被权限组使用了
        int count = permissionDao.findRelationshipByPermissionId(id);
        // count > 0 被使用了，报错
        if(count > 0){
            throw new MyException("该权限项被用户使用了，不能删除");
        }
        // =0，则可以删除
        permissionDao.deleteById(id);
    }

    @Override
    public Permission findById(int id) {
        return permissionDao.findByid(id);
    }

}
